package com.xn.monitor.web.service;

import com.xn.monitor.common.ApplicationStatus;
import com.xn.monitor.common.Constants;
import com.xn.monitor.web.entity.Application;
import com.xn.monitor.web.entity.Environment;
import com.xn.monitor.web.entity.Server;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * zookeeper数据查询服务
 *
 * Created by yangshoujun on 2017/7/15 下午12:01.
 */
@Service
public class MonitorService {

    private static ZkClient zkClient = new ZkClient(PropertyUtils.get("zk.url"));

    public List<Environment> getEnviroments() {
        List<String> envNames = zkClient.getChildren(Constants.MONITOR_BASE_PATH);
        List<Environment> envList = new ArrayList<Environment>();
        for(String envName : envNames) {
            // 过滤掉特殊节点(state, data)
            if(Arrays.asList(Constants.notEnvNode).contains(envName)) {
                continue;
            }
            Environment env = new Environment();
            env.setName(envName);
            List<Application> appList = getApplicationsByEnv(envName);
            env.setApps(appList);
            envList.add(env);
        }
        return envList;
    }

    public List<Application> getApplicationsByEnv(String env) {
        if(StringUtils.isEmpty(env)) {
            return new ArrayList<Application>();
        }
        List<String> apps = zkClient.getChildren(Constants.MONITOR_BASE_PATH + "/" + env);
        List<Application> appList = new ArrayList<Application>();
        for(String app : apps) {

            Application application = new Application();
            application.setName(app);

            List<Server> servers = getServer(env, app);
            application.setServers(servers);
            if(!servers.isEmpty()) {
                application.setStatus(ApplicationStatus.OK.getValue());
            } else {
                application.setStatus(ApplicationStatus.DOWN.getValue());
            }
            appList.add(application);
        }
        return appList;
    }

    public List<Server> getServer(String env, String app) {
        if(StringUtils.isEmpty(env)) {
            return new ArrayList<Server>();
        }
        List<String> serverInfos = zkClient.getChildren(Constants.MONITOR_BASE_PATH + "/" + env + "/" + app);
        List<Server> servers = new ArrayList<Server>();
        for(String serverName : serverInfos) {
            Server server = new Server();
            server.setServerInfo(serverName);
            servers.add(server);
        }

        return servers;
    }
}
